﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Web.Helpers;
using DotNetOpenAuth.AspNet.Clients;
using DotNetOpenAuth.Messaging;
using Microsoft.Web.WebPages.OAuth;

namespace Scrubblet.FrontEnd
{
    public static class AuthConfig
    {
        private class VkClient : OAuth2Client
        {
            private readonly string _appId;
            private readonly string _appSecret;

            public VkClient(string appId, string appSecret) : base("vk.com")
            {
                _appId = appId;
                _appSecret = appSecret;
            }

            protected override Uri GetServiceLoginUrl(Uri returnUrl)
            {
                var builder = new UriBuilder("https://oauth.vk.com/authorize");
                builder.AppendQueryArgument("client_id", _appId);
                builder.AppendQueryArgument("display", "page");
                builder.AppendQueryArgument("redirect_uri", returnUrl.AbsoluteUri);
                builder.AppendQueryArgument("response_type", "code");
                return builder.Uri;
            }

            protected override IDictionary<string, string> GetUserData(string accessToken)
            {
                var dictionary = new Dictionary<string, string>();
                using (WebResponse response = WebRequest.Create("https://api.vk.com/method/getProfiles?uid=" + _userId + "&access_token=" + accessToken).GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        var s = new StreamReader(responseStream);
                        string readToEnd = s.ReadToEnd();
                        var r = Json.Decode(readToEnd);
                        dictionary.Add("id", _userId);
                        dictionary.Add("username", r.response[0].first_name + " " + r.response[0].last_name);
                        dictionary.Add("name", r.response[0].first_name);
                    }
                }
                return dictionary;
            }

            private string _userId;

            protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
            {
                var builder = new UriBuilder("https://api.vk.com/oauth/access_token");
                builder.AppendQueryArgument("client_id", _appId);
                builder.AppendQueryArgument("client_secret", _appSecret);
                builder.AppendQueryArgument("code", authorizationCode);
                builder.AppendQueryArgument("redirect_uri", returnUrl.AbsoluteUri);


                using (var webClient = new WebClient())
                {
                    string query = webClient.DownloadString(builder.Uri);
                    if (string.IsNullOrEmpty(query)) return null;
                    var response = Json.Decode(query);
                    _userId = response.user_id.ToString();
                    return response.access_token;
                }
            }
        }

        public static void RegisterAuth()
        {
            // To let users of this site log in using their accounts from other sites such as Microsoft, Facebook, and Twitter,
            // you must update this site. For more information visit http://go.microsoft.com/fwlink/?LinkID=252166

            //OAuthWebSecurity.RegisterMicrosoftClient(
            //    clientId: "",
            //    clientSecret: "");

            //OAuthWebSecurity.RegisterTwitterClient(
            //    consumerKey: "",
            //    consumerSecret: "");

            OAuthWebSecurity.RegisterFacebookClient(
                appId: "469399596460338",
                appSecret: "48f37d096d9f617e05a346185d189d4b");

            OAuthWebSecurity.RegisterGoogleClient();

            OAuthWebSecurity.RegisterClient(new VkClient(
                appId: "3411915",
                appSecret: "ZreYHKZv3RHnBIPr1nfe"), "VK", null);
        }
    }
}
